/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import com.tengtong.duang.commons.collections.ArrayWrapper;
import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.convert.Converter;
import com.tengtong.duang.commons.convert.ConvertiblePair;
import com.tengtong.duang.commons.utils.GenericTypeResolver;

/**
 * 将一个  Converter 接口包装成一个 ConditionalConverter
 *
 * @author jai
 * @since: v1.0
 */
public class ConditionalConverterAdapter<S, T> implements ConditionalConverter{

	private final Converter<S, T> converter;
	
	private final ConvertiblePair pair;

	public ConditionalConverterAdapter(Converter<S, T> converter){
		Class<?>[] argss = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class);
		if(ArrayWrapper.wrapper(argss).notNullOrEmpty()){
			pair = new ConvertiblePair(argss[0], argss[1]);
		}else {
			pair = null;
		}
		this.converter = converter;
	}
	
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		
		return pair.matches(sourceType, targetType);
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object convert(Object source, Class targetType) {
		return converter.convert((S)source);
	}	
}
